package com.shzg.im.service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.shzg.im.dao.ICategoryDao;
import com.shzg.im.dao.IUserDao;
import com.shzg.im.model.Category;
import com.shzg.im.model.CategoryFriend;
import com.shzg.im.model.User;

@Service
public class UserService {

    @Autowired
    private IUserDao userDao;

    @Autowired
    private ICategoryDao categoryDao;

    @Transactional
    public void saveUser(User user) {
        user.setCreate_time(new Date(System.currentTimeMillis()));
        userDao.save(user);
    }

    @Transactional
    public void updateUser(User user) {
        userDao.update(user);
    }

    @Transactional
    public User getUser(String login_id) {
        return userDao.getUser(login_id);
    }

    @Transactional
    public void removeUser(String login_id) {
        userDao.delete(login_id);
    }

    public List<User> getUserList() {
        return userDao.getUserList();
    }

    public List<Category> getCategoryByUserId(String user_id) {
        return categoryDao.getCategoryByCreator(user_id);
    }

    public List<Category> getCategoryWithFriendByUserId(String user_id) {
        List<Category> catLst = categoryDao.getCategoryByCreator(user_id);
        List<CategoryFriend> catFriLst = categoryDao.getFriendByUserId(user_id);

        for (Category cat : catLst) {
            for (CategoryFriend fri : catFriLst) {
                if (cat.getId().equals(fri.getCategory_id())) {
                    cat.getFriendList().add(fri);
                }
            }
        }

        return catLst;
    }

    public List<User> searchUser(String loginId) {
        List<User> userLst = new ArrayList<User>();

        userLst = userDao.searchUser(loginId);

        return userLst;
    }

    public void addFriend(String user_id, String dest_user_id, String cat_id) {
        if (StringUtils.isEmpty(cat_id)) {
            cat_id = Category.NONCATEGORY_ID;
        }
        categoryDao.addCategoryFriend(user_id, cat_id, dest_user_id, "");
    }

    public void removeFriend(String loginId, String friId) {
        categoryDao.removeFriendByUserId(loginId, friId);
    }
}
